package com.joker.airoleplayplatformback.controller;

import com.joker.airoleplayplatformback.domain.entity.R;
import com.joker.airoleplayplatformback.service.PerformanceMonitorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 性能监控控制器
 * @author feixiang.li
 * @since 2025-09-27
 */
@Slf4j
@RestController
@RequestMapping("/api/performance")
@Tag(name = "性能监控", description = "系统性能监控相关接口")
public class PerformanceController {

    @Autowired
    private PerformanceMonitorService performanceMonitorService;

    @GetMapping("/report")
    @Operation(summary = "获取性能统计报告")
    public R<String> getPerformanceReport() {
        try {
            String report = performanceMonitorService.getPerformanceReport();
            return R.ok(report);
        } catch (Exception e) {
            log.error("获取性能报告失败", e);
            return R.error(500, "获取性能报告失败: " + e.getMessage());
        }
    }

    @GetMapping("/step-average/{stepName}")
    @Operation(summary = "获取指定步骤的平均耗时")
    public R<Map<String, Object>> getStepAverageTime(@PathVariable String stepName) {
        try {
            double avgTime = performanceMonitorService.getStepAverageTime(stepName);
            
            Map<String, Object> result = Map.of(
                "stepName", stepName,
                "averageTimeMs", avgTime,
                "averageTimeFormatted", String.format("%.1fms", avgTime)
            );
            
            return R.ok(result);
        } catch (Exception e) {
            log.error("获取步骤平均耗时失败", e);
            return R.error(500, "获取步骤平均耗时失败: " + e.getMessage());
        }
    }

    @PostMapping("/clear")
    @Operation(summary = "清空性能统计数据")
    public R<String> clearStatistics() {
        try {
            performanceMonitorService.clearStatistics();
            return R.ok("性能统计数据已清空");
        } catch (Exception e) {
            log.error("清空性能统计数据失败", e);
            return R.error(500, "清空性能统计数据失败: " + e.getMessage());
        }
    }

    @PostMapping("/check-bottleneck")
    @Operation(summary = "检查性能瓶颈")
    public R<String> checkPerformanceBottleneck() {
        try {
            performanceMonitorService.checkPerformanceBottleneck();
            return R.ok("性能瓶颈检查完成，请查看日志");
        } catch (Exception e) {
            log.error("检查性能瓶颈失败", e);
            return R.error(500, "检查性能瓶颈失败: " + e.getMessage());
        }
    }
}
